package cn.cdeden.knowledge.controller.share;


import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.FilesShare;
import cn.cdeden.knowledge.domain.dto.FilesShareDto;
import cn.cdeden.knowledge.domain.dto.ShareGetInfoDto;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.service.FilesShareService;
import cn.cdeden.knowledge.utils.MyUtil;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 链接:分文件享管理
 */
@RestController
@RequiredArgsConstructor
//@Api(tags = "链接:分文件享管理")
@RequestMapping("/api/filesShare")
public class FilesShareInfoController {

    private final FilesShareService filesShareService;

    /**
     * 分享链接:验证当前分享
     * @param hash
     * @return
     */
    @GetMapping("/annoy/valid")
//    @AnonymousGetMapping("/valid")
//    @Log("分享链接:验证当前分享")
//    @ApiOperation("分享链接:验证当前分享")
    public R valid(@RequestParam String hash) {
        FilesShare filesShare = filesShareService.getOne(new QueryWrapper<FilesShare>().eq("hash", hash).eq("status", 1));

        R baseRespResult = validationPermissions(filesShare);

        if (ObjectUtils.isNotEmpty(baseRespResult)){
            return baseRespResult;
        }

        //是否需要密码
        if (filesShare.getShareForm().intValue() == 1) {
            return R.fail( 200, "请输入文件提取密码", 412 );
//            return BaseRespResult.errorResult("412", "请输入文件提取密码");
        }

        //验证通过
        return R.ok();
//        return BaseRespResult.success();
    }

    /**
     * 分享链接:获取分享
     * @param shareGetInfoDto
     * @return
     */
//    @Log("分享链接:获取分享")
//    @ApiOperation("分享链接:获取分享")
    @PostMapping("/annoy/shareGetInfo")
//    @AnonymousPostMapping("/shareGetInfo")
    public R shareGetInfo(@RequestBody ShareGetInfoDto shareGetInfoDto) {
        FilesShare filesShare = filesShareService.getOne(new QueryWrapper<FilesShare>().
            eq("hash", shareGetInfoDto.getHash())
            .eq("status", 1));

        R baseRespResult = validationPermissions(filesShare);

        if (ObjectUtils.isNotEmpty(baseRespResult)){
            return baseRespResult;
        }
        //验证登录信息
        baseRespResult = validationPermissionsLogin(filesShare, shareGetInfoDto.getUserId());
        if (ObjectUtils.isNotEmpty(baseRespResult)){
            return baseRespResult;
        }

        if (filesShare.getShareForm() == 1) {
            if (shareGetInfoDto.getPassword() == null || "".equals(shareGetInfoDto.getPassword())) {
                return R.fail(414, "密码为空或错误");
//                return BaseRespResult.errorResult("414", "密码为空或错误");
            }
            if (!shareGetInfoDto.getPassword().equals(filesShare.getPassword())) {
                return R.fail(414, "密码为空或错误");
//                return BaseRespResult.errorResult("414", "密码为空或错误");
            }
        }

        FilesShareDto filesShareDto = filesShareService.shareGetInfo(filesShare);
        return R.ok(filesShareDto);
//        return BaseRespResult.successResult(filesShareDto);
    }


    /**
     * 分享链接:获取子级链接
     * @param shareGetInfoDto
     * @return
     */
//    @Log("分享链接:获取子级链接")
//    @ApiOperation("分享链接:获取子级链接")
    @PostMapping("/annoy/shareDirList")
//    @AnonymousPostMapping("/shareDirList")
    public R shareDirList(@RequestBody ShareGetInfoDto shareGetInfoDto) {
        FilesShare filesShare = filesShareService.getOne(new QueryWrapper<FilesShare>().eq("hash", shareGetInfoDto.getHash()).eq("status", 1));
        R baseRespResult = validationPermissions(filesShare);

        if (ObjectUtils.isNotEmpty(baseRespResult)){
            return baseRespResult;
        }

        if (filesShare.getShareForm() == 1) {
            if (shareGetInfoDto.getPassword() == null || "".equals(shareGetInfoDto.getPassword())) {
                return R.fail(414, "密码为空或错误");
//                return BaseRespResult.errorResult("414", "密码为空或错误");
            }
            if (!shareGetInfoDto.getPassword().equals(filesShare.getPassword())) {
                return R.fail(414, "密码为空或错误");
//                return BaseRespResult.errorResult("414", "密码为空或错误");
            }
        }

        //验证登录信息
        baseRespResult = validationPermissionsLogin(filesShare, shareGetInfoDto.getUserId());
        if (ObjectUtils.isNotEmpty(baseRespResult)){
            return baseRespResult;
        }


        return R.ok(filesShareService.shareDirList(shareGetInfoDto));
//        return BaseRespResult.successResult(filesShareService.shareDirList(shareGetInfoDto));
    }




    //验证登录链接权限
    private R validationPermissionsLogin(FilesShare filesShare,Long userId){
        //可访问次数不为空 并且 可访问次数小于等于0
        if (filesShare.getVisitsNumber() != null && filesShare.getVisitsNumber().intValue() <= 0) {
            return R.fail(416, "超过访问上限");
//            return BaseRespResult.errorResult("416", "超过访问上限");
        }

        String shareType = filesShare.getShareType();

        TreeEnum treeEnum = TreeEnum.find(shareType);
        switch (treeEnum) {
//            case TEAM:
//                if (filesShare.isTeamType()) {
//                    String teamId = filesShare.getTeamId();
//                    if (StringUtils.isBlank(teamId))  return R.fail(415, "当前用户没有权限查看");
////                    if (StringUtils.isBlank(teamId))  return BaseRespResult.errorResult("415", "当前用户没有权限查看");
//                    List<TeamMemberDto> teamMemberDtos = teamMemberService.getTeamByMemberDto(FileUserUtils.getUser().getId());
//                    boolean b = false;
//                    for (TeamMemberDto teamMemberDto : teamMemberDtos) {
//                        if (String.valueOf(teamMemberDto.getTeamId()).equals(teamId)){
//                            b = true;
//                            break;
//                        }
//                    }
//                    if (!b) return BaseRespResult.errorResult("415", "当前用户没有权限查看");
//                }
            case PERSONAL:
                if (StringUtils.isNotBlank(filesShare.getAccessibleId())) {
                    Boolean flag = false;
                    String[] split = filesShare.getAccessibleId().split(",");
                    try {
                        //分享人可以访问
                        userId = LoginHelper.getLoginUser().getUserId();
//                        userId = FileUserUtils.getUser().getId();

                        if (filesShare.getPersonId().intValue() == userId) {
                            flag = true;
                        }
                        //可访问者可以访问
                        if (!flag) {
                            for (int i = 0; i < split.length; i++) {
                                if (split[i].equals(userId.toString())) {
                                    flag = true;
                                    break;
                                }
                            }
                        }

                        if (!flag) {
                            return R.fail(415, "当前用户没有权限查看");
//                            return BaseRespResult.errorResult("415", "当前用户没有权限查看");
                        }

                    }catch (Exception e){
                        if (StringUtils.isNoneBlank(filesShare.getAccessibleId())) {
                            return R.fail(413, "访问该分享链接需要登录!账号");
//                            return BaseRespResult.errorResult("413", "访问该分享链接需要登录!账号");
                        }
                    }
                }
                break;
            default:
                break;
        }
        return null;
    }




    //验证链接权限
    private R validationPermissions(FilesShare filesShare){
        if (filesShare == null) {
            return R.fail(411, "当前分享链接不存在");
//            return BaseRespResult.errorResult("411", "当前分享链接不存在");
        }

        if(filesShare.getDeadline() != null){
            if (MyUtil.isDeadTime(filesShare.getDeadline())) {
                return R.fail(417, "当前分享链接已过期");
//                return BaseRespResult.errorResult("417", "当前分享链接已过期");
            }
        }
        //获取不到当前的用户信息 就判断当前的分享链接是否需要用户
        try {
            LoginUser user = LoginHelper.getLoginUser();
//            FileUserDto user = FileUserUtils.getUser();
        } catch (Exception e) {
            if (StringUtils.isNotBlank(filesShare.getAccessibleId()) || filesShare.isTeamType()) {
                return R.fail(413, "访问该分享链接需要登录!账号");
//                return BaseRespResult.errorResult("413", "访问该分享链接需要登录!账号");
            }
        }
        return null;
    }



}
